﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Aioms.Model;
using Aioms.Models;
using Furion.DataEncryption;
using Furion.DynamicApiController;
using Furion.LinqBuilder;
using Furion.UnifyResult;
using Masuit.Tools;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SqlSugar;
using StackExchange.Profiling.Internal;

namespace Aioms.Controllers
{
    /// <summary>
    /// 废弃的接口
    /// </summary>
    [DynamicApiController]
    public class WorkOrderController
    {
        private readonly ISqlSugarClient db; // 核心对象：拥有完整的SqlSugar全部功能
        public WorkOrderController(ISqlSugarClient sqlSugarClient)
        {
            this.db = sqlSugarClient;
        }

        /// <summary>
        /// PC端-安卓端-工单列表
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="epid"></param>
        /// <param name="content"></param>
        /// <param name="type"></param>
        /// <param name="created"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostList([FromForm] long eid, [FromForm] long epid, [FromForm] string content, [FromForm] string type, [FromForm] DateTime created, [FromForm] int pageIndex = 1, [FromForm] int pageSize = 10)
        {
            // 先筛选出来指派给我的所有工单
            //List<long> woids = await db.Queryable<WorkOrderEmployee>().Where(woe => woe.Eid == eid)
            //    .WhereIF(epid != 0, woe => woe.Epid == epid)
            //    .Select(woe => woe.Woid).ToListAsync();

            RefAsync<int> dbTotal = 0;
            List<WorkOrder> db_workorders = await db.Queryable<WorkOrder>()
                .Where(wo => wo.Eid == eid)
                .Where(wo => wo.Status == "待接单")
                .WhereIF(epid != 0, $"FIND_IN_SET({epid}, epids)")
                .WhereIF(!string.IsNullOrEmpty(content), wo => wo.Name.Contains(content))
                .WhereIF(!string.IsNullOrEmpty(type), wo => wo.Type == type)
                .WhereIF(created != DateTime.MinValue, wo => SqlFunc.DateIsSame(wo.Created, created, DateType.Day))
                .OrderBy(wo => wo.Id, OrderByType.Desc)
                .ToPageListAsync(pageIndex, pageSize, dbTotal);

            RefAsync<int> wksTotal = 0;
            List<WorkOrder> wks_workorders = await db.Queryable<WorkOrder>()
                .Where(wo => wo.Eid == eid)
                .Where(wo => wo.Status == "未开始")
                .WhereIF(epid != 0, $"FIND_IN_SET({epid}, epids)")
                .WhereIF(!string.IsNullOrEmpty(content), wo => wo.Name.Contains(content))
                .WhereIF(!string.IsNullOrEmpty(type), wo => wo.Type == type)
                .WhereIF(created != DateTime.MinValue, wo => SqlFunc.DateIsSame(wo.Created, created, DateType.Day))
                .OrderBy(wo => wo.Id, OrderByType.Desc)
                .ToPageListAsync(pageIndex, pageSize, dbTotal);

            RefAsync<int> jxzTotal = 0;
            List<WorkOrder> jxz_workorders = await db.Queryable<WorkOrder>()
                .Where(wo => wo.Eid == eid)
                .Where(wo => wo.Status == "进行中")
                .WhereIF(epid != 0, $"FIND_IN_SET({epid}, epids)")
                .WhereIF(!string.IsNullOrEmpty(content), wo => wo.Name.Contains(content))
                .WhereIF(!string.IsNullOrEmpty(type), wo => wo.Type == type)
                .OrderBy(wo => wo.Id, OrderByType.Desc)
                .ToPageListAsync(pageIndex, pageSize, jxzTotal);

            RefAsync<int> ywcTotal = 0;
            List<WorkOrder> ywc_workorders = await db.Queryable<WorkOrder>()
                .Where(wo => wo.Eid == eid)
                .Where(wo => wo.Status == "已完成")
                .WhereIF(epid != 0, $"FIND_IN_SET({epid}, epids)")
                .WhereIF(!string.IsNullOrEmpty(content), wo => wo.Name.Contains(content))
                .WhereIF(!string.IsNullOrEmpty(type), wo => wo.Type == type)
                .OrderBy(wo => wo.Id, OrderByType.Desc)
                .ToPageListAsync(pageIndex, pageSize, ywcTotal);

            JObject data = new();
            data.Add("daiban", db_workorders == null ? null : JArray.FromObject(db_workorders));
            data.Add("weikaishi", wks_workorders == null ? null : JArray.FromObject(wks_workorders));
            data.Add("jinxingzhong", jxz_workorders == null ? null : JArray.FromObject(jxz_workorders));
            data.Add("yiwancheng", ywc_workorders == null ? null : JArray.FromObject(ywc_workorders));

            UnifyContext.Fill(new { DbTotal = dbTotal, WksTotal = wksTotal, JxzTotal = jxzTotal, YwcTotal = ywcTotal });
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = data,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 安卓端-工单列表
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="epid"></param>
        /// <param name="content"></param>
        /// <param name="type"></param>
        /// <param name="begintime"></param>
        /// <param name="status"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostAlist([FromForm] long eid, [FromForm] long epid, [FromForm] string content, [FromForm] string type, [FromForm] DateTime begintime, [FromForm] string status, [FromForm] int pageIndex = 1, [FromForm] int pageSize = 10)
        {

            RefAsync<int> total = 0;
            List<WorkOrder> workorders = await db.Queryable<WorkOrder>()
                .Where(wo => wo.Eid == eid)
                .WhereIF(!string.IsNullOrEmpty(status), wo => wo.Status == status)
                .WhereIF(epid != 0, $"FIND_IN_SET({epid}, epids)")
                .WhereIF(!string.IsNullOrEmpty(content), wo => wo.Name.Contains(content))
                .WhereIF(!string.IsNullOrEmpty(type), wo => wo.Type == type)
                .WhereIF(begintime != DateTime.MinValue, wo => wo.BeginTime.Date == begintime.Date)
                .OrderBy(wo => wo.Id, OrderByType.Desc)
                .ToPageListAsync(pageIndex, pageSize, total);

            foreach (var workorder in workorders)
            {
                if (!string.IsNullOrEmpty(workorder.Epids))
                {
                    List<long> epids = workorder.Epids.Split(",", StringSplitOptions.RemoveEmptyEntries).Select(long.Parse).ToList();
                    workorder.Employees = await db.Queryable<Employee>().Where(ep => epids.Contains(ep.Id)).ToListAsync();
                }
                if (workorder.Source.Equals("报修"))
                {
                    workorder.NoticeRepair = await db.Queryable<NoticeRepair>().Where(np => np.Id == workorder.RefId).SingleAsync();
                }
                if (workorder.Source.Equals("计划"))
                {
                    workorder.TaskPlan = await db.Queryable<TaskPlan>().Where(tp => tp.Id == workorder.RefId).SingleAsync();
                    if (workorder.TaskPlan != null)
                    {
                        if (workorder.TaskPlan.Source.Equals("line"))
                        {
                            workorder.TaskPlan.InspectionLine = await db.Queryable<InspectionLine>().Where(il => il.Id == long.Parse(workorder.TaskPlan.RefIds)).SingleAsync();
                            workorder.TaskPlan.InspectionLine.InspectionPoints = await db.Queryable<InspectionPoint>().Where(ip => ip.Ilid == workorder.TaskPlan.InspectionLine.Id).ToListAsync();
                        }
                        else
                        {
                            workorder.TaskPlan.Devices = await db.Queryable<Device>().Where($"FIND_IN_SET(id, '{workorder.TaskPlan.RefIds}')").ToListAsync();
                        }
                    }
                }
            }

            UnifyContext.Fill(new { Total = total });
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = workorders,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 眼镜端-工单列表
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="epid"></param>
        /// <param name="content"></param>
        /// <param name="type"></param>
        /// <param name="begintime"></param>
        /// <param name="status"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostVrlist([FromForm] long eid, [FromForm] long epid, [FromForm] string content, [FromForm] string type, [FromForm] DateTime begintime, [FromForm] string status, [FromForm] int pageIndex = 1, [FromForm] int pageSize = 10)
        {

            RefAsync<int> total = 0;
            List<WorkOrder> workorders = await db.Queryable<WorkOrder>()
                .Where(wo => wo.Eid == eid)
                .Where(wo => wo.Status != "已完成")
                .WhereIF(epid != 0, $"FIND_IN_SET({epid}, epids)")
                .WhereIF(!string.IsNullOrEmpty(content), wo => wo.Name.Contains(content))
                .WhereIF(!string.IsNullOrEmpty(type), wo => wo.Type == type)
                .WhereIF(begintime != DateTime.MinValue, wo => wo.BeginTime.Date == begintime.Date)
                .OrderBy(wo => wo.Id, OrderByType.Desc)
                .ToPageListAsync(pageIndex, pageSize, total);

            foreach (var workorder in workorders)
            {
                if (!string.IsNullOrEmpty(workorder.Epids))
                {
                    List<long> epids = workorder.Epids.Split(",", StringSplitOptions.RemoveEmptyEntries).Select(long.Parse).ToList();
                    workorder.Employees = await db.Queryable<Employee>().Where(ep => epids.Contains(ep.Id)).ToListAsync();
                }
                if (workorder.Source.Equals("报修"))
                {
                    workorder.NoticeRepair = await db.Queryable<NoticeRepair>().Where(np => np.Id == workorder.RefId).SingleAsync();
                }
                if (workorder.Source.Equals("计划"))
                {
                    workorder.TaskPlan = await db.Queryable<TaskPlan>().Where(tp => tp.Id == workorder.RefId).SingleAsync();
                    if (workorder.TaskPlan != null)
                    {
                        if (workorder.TaskPlan.Source.Equals("line"))
                        {
                            workorder.TaskPlan.InspectionLine = await db.Queryable<InspectionLine>().Where(il => il.Id == long.Parse(workorder.TaskPlan.RefIds)).SingleAsync();
                            workorder.TaskPlan.InspectionLine.InspectionPoints = await db.Queryable<InspectionPoint>().Where(ip => ip.Ilid == workorder.TaskPlan.InspectionLine.Id).ToListAsync();
                        }
                        else
                        {
                            workorder.TaskPlan.Devices = await db.Queryable<Device>().Where($"FIND_IN_SET(id, '{workorder.TaskPlan.RefIds}')").ToListAsync();
                        }
                    }
                }
            }

            UnifyContext.Fill(new { Total = total });
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = workorders,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 新增工单
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="workorder"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostSave([FromForm] long eid, [FromForm] WorkOrder workorder)
        {
            long id = await db.Insertable<WorkOrder>(workorder).ExecuteReturnIdentityAsync();

            // 如果指派员工
            if (workorder.Epids?.Length > 0)
            {
                List<WorkOrderEmployee> workOrderEmployees = new();
                foreach (var epid in workorder.Epids)
                {
                    workOrderEmployees.Add(new WorkOrderEmployee { Eid = eid, Woid = id, Epid = epid });
                }
                await db.Insertable<WorkOrderEmployee>(workOrderEmployees).ExecuteCommandAsync();
            }

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostDelete([FromForm] long eid, [FromForm] long id)
        {
            await db.Deleteable<WorkOrder>().Where(wo => wo.Eid == eid && wo.Id == id).ExecuteCommandAsync();

            await db.Deleteable<WorkOrderEmployee>().Where(wo => wo.Eid == eid && wo.Woid == id).ExecuteCommandAsync();

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="workorder"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostUpdate([FromForm] long eid, [FromForm] WorkOrder workorder)
        {
            await db.Updateable<WorkOrder>(workorder).ExecuteCommandAsync();

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// PC端-安卓端-查看
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostShow([FromForm] long eid, [FromForm] long id)
        {
            WorkOrder workorder = await db.Queryable<WorkOrder>().Where(wo => wo.Eid == eid && wo.Id == id).SingleAsync();
            TaskPlan taskplan = null;
            NoticeRepair noticerepair = null;
            Device device = null;
            List<Device> devices = null;
            Area area = null;
            InspectionLine inspectionline = null;
            List<InspectionPoint> inspectionpoints = null;

            List<long> finished_ipids = null;
            List<long> finished_dvids = null;
            if (workorder.Source.Equals("报修"))
            {
                noticerepair = await db.Queryable<NoticeRepair>().Where(nr => nr.Id == workorder.RefId).SingleAsync();
                device = await db.Queryable<Device>().Where(d => d.Id == noticerepair.Dvid).SingleAsync();
                area = await db.Queryable<Area>().Where(a => a.Id == device.Aeid).SingleAsync();
            }
            else
            {
                taskplan = await db.Queryable<TaskPlan>().Where(tp => tp.Id == workorder.RefId).SingleAsync();
                if (taskplan.Source == "line")
                {
                    inspectionline = await db.Queryable<InspectionLine>().Where(il => il.Id == long.Parse(taskplan.RefIds)).SingleAsync();
                    inspectionpoints = await db.Queryable<InspectionPoint>().Where(ip => ip.Ilid == long.Parse(taskplan.RefIds)).ToListAsync();

                    // 查看已经做过的设备ID列表
                    finished_ipids = await db.Queryable<InspectionPointOptionResult>()
                        .Where(ipor => ipor.Eid == eid && ipor.Woid == workorder.Id)
                        .Select(ipor => ipor.Ipid)
                        .ToListAsync();
                }
                else
                {
                    List<long> dvids = taskplan.RefIds.Split(",", StringSplitOptions.RemoveEmptyEntries).Select(long.Parse).ToList();
                    devices = await db.Queryable<Device>().Where(d => dvids.Contains(d.Id)).ToListAsync();

                    // 查看已经做过的设备ID列表
                    finished_dvids = await db.Queryable<DeviceStandardResult>()
                        .Where(dsr => dsr.Eid == eid && dsr.Woid == workorder.Id)
                        .Select(dsr => dsr.Dvid)
                        .ToListAsync();
                }
            }

            UnifyContext.Fill(new { TaskPlan = taskplan, NoticeRepair = noticerepair, Device = device, Area = area, Devices = devices, InspectionLine = inspectionline, InspectionPoints = inspectionpoints, FinishedIpids = finished_ipids, FinishedDvids = finished_dvids });

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = workorder,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// PC端-安卓端-派单
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="woid"></param>
        /// <param name="pdlx"></param>
        /// <param name="epids"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostPaidan([FromForm] long eid, [FromForm] long woid, [FromForm] DateTime begintime, [FromForm] DateTime endtime, [FromForm] int manhour, [FromForm] string pdlx, [FromForm] long[] epids)
        {
            // 清空之前企业该工单指派员工
            //await db.Deleteable<WorkOrderEmployee>().Where(wo => wo.Eid == eid && wo.Woid == woid).ExecuteCommandAsync();

            if (pdlx.Equals("部门"))
            {
                //// 查询该企业所有员工
                //List<long> allepid = await db.Queryable<EmployeeEnterprise>().Where(ee => ee.Eid == eid).Select(ee => ee.Epid).ToListAsync();
                //// 根据所有员工筛选出来指定部门下的所有员工
                //List<long> epidsofdepartment = await db.Queryable<Employee>().Where(e => allepid.Contains(e.Id) && e.Dpid == epids.First()).Select(e => e.Id).ToListAsync();
                //if (epidsofdepartment.Count > 0) {
                //    List<WorkOrderEmployee> workOrderEmployees = new();
                //    foreach (var epid in epidsofdepartment)
                //    {
                //        workOrderEmployees.Add(new WorkOrderEmployee { Eid = eid, Woid = woid, Epid = epid });
                //    }
                //    await db.Insertable<WorkOrderEmployee>(workOrderEmployees).ExecuteCommandAsync();
                //}
                List<long> epidslist = await db.Queryable<Employee>().Where(ep => ep.DefaultEid == eid && ep.Dpid == epids.First()).Select(ep => ep.Id).ToListAsync();
                await db.Updateable<WorkOrder>()
                    .SetColumns(wo => wo.Epids == string.Join(",", epidslist))
                    .SetColumns(wo => wo.BeginTime == begintime)
                    .SetColumns(wo => wo.EndTime == endtime)
                    .SetColumns(wo => wo.ManHour == manhour)
                    .SetColumns(wo => wo.Status == "未开始")
                    .Where(wo => wo.Id == woid && wo.Eid == eid)
                    .ExecuteCommandAsync();
            }
            else
            {
                //if (epids.Length > 0)
                //{
                //    List<WorkOrderEmployee> workOrderEmployees = new();
                //    foreach (var epid in epids)
                //    {
                //        workOrderEmployees.Add(new WorkOrderEmployee { Eid = eid, Woid = woid, Epid = epid });
                //    }
                //    await db.Insertable<WorkOrderEmployee>(workOrderEmployees).ExecuteCommandAsync();
                //}
                await db.Updateable<WorkOrder>()
                    .SetColumns(wo => wo.Epids == string.Join(",", epids))
                    .SetColumns(wo => wo.BeginTime == begintime)
                    .SetColumns(wo => wo.EndTime == endtime)
                    .SetColumns(wo => wo.ManHour == manhour)
                    .SetColumns(wo => wo.Status == "未开始")
                    .Where(wo => wo.Id == woid && wo.Eid == eid)
                    .ExecuteCommandAsync();
            }

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 安卓端-新派单接口
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="woid"></param>
        /// <param name="begintime"></param>
        /// <param name="endtime"></param>
        /// <param name="manhour"></param>
        /// <param name="pdlx"></param>
        /// <param name="epids"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostApaidan([FromForm] long eid, [FromForm] long woid, [FromForm] DateTime begintime, [FromForm] DateTime endtime, [FromForm] int manhour, [FromForm] string pdlx, [FromForm] string epids)
        {
            // 清空之前企业该工单指派员工
            //await db.Deleteable<WorkOrderEmployee>().Where(wo => wo.Eid == eid && wo.Woid == woid).ExecuteCommandAsync();

            if (pdlx.Equals("部门"))
            {
                //// 查询该企业所有员工
                //List<long> allepid = await db.Queryable<EmployeeEnterprise>().Where(ee => ee.Eid == eid).Select(ee => ee.Epid).ToListAsync();
                //// 根据所有员工筛选出来指定部门下的所有员工
                //List<long> epidsofdepartment = await db.Queryable<Employee>().Where(e => allepid.Contains(e.Id) && e.Dpid == epids.First()).Select(e => e.Id).ToListAsync();
                //if (epidsofdepartment.Count > 0) {
                //    List<WorkOrderEmployee> workOrderEmployees = new();
                //    foreach (var epid in epidsofdepartment)
                //    {
                //        workOrderEmployees.Add(new WorkOrderEmployee { Eid = eid, Woid = woid, Epid = epid });
                //    }
                //    await db.Insertable<WorkOrderEmployee>(workOrderEmployees).ExecuteCommandAsync();
                //}
                List<long> epidslist = await db.Queryable<Employee>().Where(ep => ep.DefaultEid == eid && ep.Dpid == epids.First()).Select(ep => ep.Id).ToListAsync();
                await db.Updateable<WorkOrder>()
                    .SetColumns(wo => wo.Epids == string.Join(",", epidslist))
                    .SetColumns(wo => wo.BeginTime == begintime)
                    .SetColumns(wo => wo.EndTime == endtime)
                    .SetColumns(wo => wo.ManHour == manhour)
                    .SetColumns(wo => wo.Status == "未开始")
                    .Where(wo => wo.Id == woid && wo.Eid == eid)
                    .ExecuteCommandAsync();
            }
            else
            {
                //if (epids.Length > 0)
                //{
                //    List<WorkOrderEmployee> workOrderEmployees = new();
                //    foreach (var epid in epids)
                //    {
                //        workOrderEmployees.Add(new WorkOrderEmployee { Eid = eid, Woid = woid, Epid = epid });
                //    }
                //    await db.Insertable<WorkOrderEmployee>(workOrderEmployees).ExecuteCommandAsync();
                //}
                await db.Updateable<WorkOrder>()
                    .SetColumns(wo => wo.Epids == epids)
                    .SetColumns(wo => wo.BeginTime == begintime)
                    .SetColumns(wo => wo.EndTime == endtime)
                    .SetColumns(wo => wo.ManHour == manhour)
                    .SetColumns(wo => wo.Status == "未开始")
                    .Where(wo => wo.Id == woid && wo.Eid == eid)
                    .ExecuteCommandAsync();
            }

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 安卓端-接单
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="woid"></param>
        /// <param name="begintime"></param>
        /// <param name="endtime"></param>
        /// <param name="manhour"></param>
        /// <param name="epids"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostJiedan([FromForm] long eid, [FromForm] long woid, [FromForm] DateTime begintime, [FromForm] DateTime endtime, [FromForm] int manhour, [FromForm] long[] epids)
        {
            await db.Updateable<WorkOrder>()
                .SetColumns(wo => wo.Epids == string.Join(",", epids))
                .SetColumns(wo => wo.BeginTime == begintime)
                .SetColumns(wo => wo.EndTime == endtime)
                .SetColumns(wo => wo.ManHour == manhour)
                .SetColumns(wo => wo.Status == "未开始")
                .Where(wo => wo.Id == woid && wo.Eid == eid)
                .ExecuteCommandAsync();

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }



        /// <summary>
        /// 安卓端-我的-今日完成
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="epid"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostJinriwancheng([FromForm] long eid, [FromForm] long epid)
        {
            // 先筛选出来指派给我的所有工单
            //List<long> woids = await db.Queryable<WorkOrderEmployee>().Where(woe => woe.Eid == eid && woe.Epid == epid).Select(woe => woe.Woid).ToListAsync();

            int jrwc_total = await db.Queryable<WorkOrder>()
                .Where(wo => wo.Eid == eid)
                .Where($"FIND_IN_SET({epid}, epids)")
                .Where(wo => wo.Status == "已完成")
                .Where(wo => wo.SjEndTime.Date == DateTime.Now.Date)
                .CountAsync();

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = jrwc_total,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 安卓端-首页-待办计划
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="epid"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostDaibanjihua([FromForm] long eid, [FromForm] long epid)
        {
            // 先筛选出来指派给我的所有工单
            //List<long> woids = await db.Queryable<WorkOrderEmployee>().Where(woe => woe.Eid == eid && woe.Epid == epid).Select(woe => woe.Woid).ToListAsync();

            int dbjh_total = await db.Queryable<WorkOrder>()
                .Where(wo => wo.Eid == eid)
                .Where($"FIND_IN_SET({epid}, epids)")
                .Where(wo => wo.Source == "计划")
                .Where(wo => wo.Status == "未开始")
                .CountAsync();

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = dbjh_total,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 安卓端-首页-待办维修
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="epid"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostDaibanweixiu([FromForm] long eid, [FromForm] long epid)
        {
            // 先筛选出来指派给我的所有工单
            //List<long> woids = await db.Queryable<WorkOrderEmployee>().Where(woe => woe.Eid == eid && woe.Epid == epid).Select(woe => woe.Woid).ToListAsync();

            int dbwx_total = await db.Queryable<WorkOrder>()
                .Where(wo => wo.Eid == eid)
                .Where($"FIND_IN_SET('{epid}', epids)")
                .Where(wo => wo.Source == "报修")
                .Where(wo => wo.Status == "未开始")
                .CountAsync();

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = dbwx_total,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 获取指派人
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="woid"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostGetzhipairen([FromForm] long eid, [FromForm] long woid)
        {
            List<Employee> employees = new();
            List<long> epids = await db.Queryable<WorkOrderEmployee>().Where(woe => woe.Eid == eid && woe.Woid == woid).Select(woe => woe.Epid).ToListAsync();
            if (epids.Count > 0)
            {
                employees = await db.Queryable<Employee>().Where(e => epids.Contains(e.Id)).ToListAsync();
            }

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = employees,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 安卓端-更新工单状态
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="woid"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostUpdatestatus([FromForm] long eid, [FromForm] long woid, [FromForm] string status)
        {
            await db.Updateable<WorkOrder>()
                .SetColumns(wo => wo.Status == status)
                .Where(wo => wo.Eid == eid && wo.Id == woid)
                .ExecuteCommandAsync();

            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 安卓端-眼镜端-更新开始时间
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="woid"></param>
        /// <param name="begintime"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostUpdatebegintime([FromForm] long eid, [FromForm] long woid, [FromForm] DateTime begintime)
        {
            WorkOrder last_workorder = await db.Queryable<WorkOrder>().Where(wo => wo.Eid == eid && wo.Id == woid).SingleAsync();
            if (last_workorder.SjBeginTime == DateTime.MinValue)
            {
                await db.Updateable<WorkOrder>()
                    .SetColumns(wo => wo.SjBeginTime == begintime)
                    .SetColumns(wo => wo.Status == "进行中")
                    .Where(wo => wo.Eid == eid && wo.Id == woid).ExecuteCommandAsync();
            }
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 安卓端-眼镜端-更新结束时间
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="woid"></param>
        /// <param name="endtime"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostUpdateendtime([FromForm] long eid, [FromForm] long woid, [FromForm] DateTime endtime)
        {
            DateTime begintime = await db.Queryable<WorkOrder>().Where(wo => wo.Eid == eid && wo.Id == woid).Select(wo => wo.SjBeginTime).SingleAsync();
            await db.Updateable<WorkOrder>()
                .SetColumns(wo => wo.SjEndTime == endtime)
                .SetColumns(wo => wo.SjManHour == (endtime - begintime).TotalHours.ToDecimal())
                .SetColumns(wo => wo.Status == "已完成")
                .Where(wo => wo.Eid == eid && wo.Id == woid).ExecuteCommandAsync();
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }
    }
}
